/************************************************************
 *  * EaseMob CONFIDENTIAL
 * __________________
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of EaseMob Technologies.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from EaseMob Technologies.
 */

#import "GroupSubjectChangingViewController.h"

#define MAX_STARWORDS_LENGTH 42
@interface GroupSubjectChangingViewController () <UITextFieldDelegate>
{
    EMGroup         *_group;
    BOOL            _isOwner;
    UITextField     *_subjectField;
    UILabel *totalLabel;
    UIButton *cancelBtn;
}

@end

@implementation GroupSubjectChangingViewController

- (instancetype)initWithGroup:(EMGroup *)group
{
    self = [self init];
    if (self) {
        _group = group;
        NSString *loginUsername = [[EMClient sharedClient] currentUsername];
        _isOwner = [_group.owner isEqualToString:loginUsername];
        self.view.backgroundColor = RGB(238, 238, 238);
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"title.groupSubjectChanging", @"Change group name");
    

    
    _subjectField = [[UITextField alloc] init];
//    _subjectField.layer.cornerRadius = 5.0;
    _subjectField.layer.borderWidth = 0.1;
    _subjectField.placeholder = NSLocalizedString(@"group.setting.subject", @"Please input group name");
    _subjectField.text = _group.subject;
    _subjectField.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _subjectField.backgroundColor = [UIColor whiteColor];//文本输入框的底部颜色为白色
    if (!_isOwner) {
//        UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
//        [backButton setImage:[UIImage imageNamed:@"HuanXin.bundle/back.png"] forState:UIControlStateNormal];
//        [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
//        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
//        [self.navigationItem setLeftBarButtonItem:backItem];
        _subjectField.enabled = NO;
    }
    if (_isOwner) {
        //左
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
        [self.navigationItem setLeftBarButtonItem:backItem];
        //右
        UIBarButtonItem *saveItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"save", @"Save") style:UIBarButtonItemStylePlain target:self action:@selector(save:)];
        [self.navigationItem setRightBarButtonItem:saveItem];
    }
    
    UIView *holder = [[UIView alloc] initWithFrame:CGRectMake(_subjectField.frame.size.width-50, 0, 50, 50)];
    
    cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(15,15,20,20)];
    [cancelBtn setImage:[UIImage imageNamed:@"HuanXin.bundle/group_nameEdit_cancel"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [holder addSubview:cancelBtn];
    _subjectField.rightView = holder;
    _subjectField.rightViewMode = UITextFieldViewModeAlways;
   
    holder = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 15.0, 50)];
    _subjectField.leftView = holder;
    _subjectField.leftViewMode = UITextFieldViewModeAlways;
    _subjectField.delegate = self;
    _subjectField.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:_subjectField];
    
    //添加两个说明的label
    totalLabel = [[UILabel alloc] init];
    totalLabel.translatesAutoresizingMaskIntoConstraints = NO;
    totalLabel.text = [NSString stringWithFormat:@"%lu/42",(unsigned long)_group.subject.length];
    totalLabel.textAlignment = NSTextAlignmentLeft;
    totalLabel.textColor = [UIColor lightGrayColor];//字体为灰色
    [self.view addSubview:totalLabel];
    
    //进行布局
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_subjectField) format:@"H:|[_subjectField]|"]];
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(totalLabel) format:@"H:[totalLabel]-15-|"]];
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_subjectField,totalLabel) format:@"V:|-20-[_subjectField(50)]-[totalLabel(25)]"]];

    if (!_isOwner) {
        holder.hidden = YES;
        cancelBtn.hidden = YES;
        totalLabel.hidden = YES;
    }
    //添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:_subjectField];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Notification Method
#pragma mark - 计算当前UITextView中的字的数量

- (void)textFieldEditChanged:(NSNotification *)object {
    UITextField *textF = (UITextField *)object.object;
    NSString *toBeString = textF.text;
    //键盘输入模式
    NSArray *currentAr = [UITextInputMode activeInputModes];
    UITextInputMode *current = [currentAr firstObject];
    
    if ([current.primaryLanguage isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textF markedTextRange];//获取高亮部分
        UITextPosition *position = [textF positionFromPosition:selectedRange.start offset:0];
       
        //没有高亮的字，则对已输入的问题进行字数统计和限制
        if (!position) {
            if (toBeString.length >MAX_STARWORDS_LENGTH) {
                textF.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
            }
            totalLabel.text = [NSString stringWithFormat:@"%lu/42",(unsigned long)textF.text.length];
        }else//中文输入法以外的直接对其统计限制即可，不考虑其它语种状况；
        {
            if (toBeString.length > MAX_STARWORDS_LENGTH){
                NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
                if (rangeIndex.length == 1) {
                    textF.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
                }else {
                    NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
                    textF.text = [toBeString substringWithRange:rangeRange];
                }
            }
            totalLabel.text = [NSString stringWithFormat:@"%lu/42",(unsigned long)textF.text.length];
        }
        totalLabel.text = [NSString stringWithFormat:@"%lu/42",(unsigned long)textF.text.length];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - action
- (void)cancelAction {
    if (_isOwner) {
        _subjectField.text = nil;
        totalLabel.text = @"0/42";
    }
}
- (void)back
{
    if ([_subjectField isFirstResponder])
    {
        [_subjectField resignFirstResponder];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)save:(id)sender
{
    [self saveSubject];
}

- (void)saveSubject
{
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:_group.groupId type:EMConversationTypeGroupChat createIfNotExist:NO];
    EMError *error = nil;
    [[EMClient sharedClient].groupManager changeGroupSubject:_subjectField.text forGroup:_group.groupId error:&error];
//    [[EMClient sharedClient].groupManager changeDescription:@"12312312" forGroup:_group.groupId error:&error];
    if (!error) {
        if ([_group.groupId isEqualToString:conversation.conversationId]) {
            NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:conversation.ext];
            [ext setObject:_group.subject forKey:@"subject"];
            [ext setObject:[NSNumber numberWithBool:_group.isPublic] forKey:@"isPublic"];
            conversation.ext = ext;
        }
    }
    [self back];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:@"UITextFieldTextDidChangeNotification"
                                                 object:_subjectField];
}
@end
